#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
from urllib.parse import unquote

import scrapy
import re

from lxml import etree

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, base64
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class YunnanYnsrmzf0150Policy(BaseTaxPolicySpider):
    name = 'yunnan_ynnync_policy'

    source = '云南省发展与改革委员会'
    province = '云南省'
    city = ''
    county = ''
    park = ''

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                # "COOKIES_ENABLED": False,
                "DOWNLOAD_TIMEOUT": 200,
                # "CONCURRENT_REQUESTS": 2,
                "HTTPERROR_ALLOWED_CODES": [302, 400, 404, 407, 500, 200, 202, 502, 429, 521],
                # "DOWNLOAD_DELAY": 5,
                "DOWNLOADER_MIDDLEWARES": {
                    # "components.middlewares.downloadmiddlewares.public.jsl_middlewares.JslMiddleware": 543,
                    **downloader_middlewares
                }
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url in [
            ['云南省农业农村厅', '', 'https://nync.yn.gov.cn/html/zhengwugongkai/zhengcewenjian-new/guifanxingwenjian-new/#tp'],
            ['云南省农业农村厅', '', 'https://nync.yn.gov.cn/html/zhengwugongkai/zhengcewenjian-new/zuixinwenjian/#tp'],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={"item": item})

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.xpath(
                "//div[@class='item_a']//td[@class='fl title']//a[contains(@href, 'htm') or @title]/ancestor::td[string-length(string(.))>=10] |"
                "//table[@class='table']//td//a[contains(@href, 'htm') or @title]/ancestor::td[string-length(string(.))>=10]"):
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*/.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url'] and '.jhtm' not in item['source_url']:
                continue
            # print(item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            page_text = response.xpath("""//*[@id='pages']/text()""").get()
            # 解码Base64字符串
            decoded_bytes = base64.b64decode(page_text)
            # 转换为字符串
            decoded_string = unquote(decoded_bytes.decode('utf-8'))
            next_page = etree.HTML(decoded_string.replace('+', ' ')).xpath('//a[text()="下一页"]/@href')
            self.logger.debug("")
            if next_page:
                yield response.follow(next_page[0], callback=self.parse_list, meta={'item': prev_item})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("""string(//meta[@name='pubdate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl yunnan_ynnync_policy".split())
